package org.example.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception {
        if (msg instanceof TextWebSocketFrame) {
            // text文本
            TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) msg;
            log.info("收到客户端msg = {}", textWebSocketFrame.text());

            // 回写服务端
            TextWebSocketFrame respFrame = new TextWebSocketFrame("from server :" + textWebSocketFrame.text());
            ctx.channel().writeAndFlush(respFrame);
        } else {
            String message = "unsupported frame type : " + msg.getClass().getName();
            throw new UnsupportedOperationException(message);
        }
    }
}
